import ReconnectingWebSocket from 'reconnecting-websocket';

let rws= null;
let globalCallback= null;

//初始化websocket
const initWebsocket = () => {
  let url = "ws://localhost:8089/ws/100";
  // 建立websocket 连接
  rws = new ReconnectingWebSocket(url);
  rws.addEventListener("open", () => {
    if (!rws) return;
    if (rws.readyState === 1) {
      webSocketOpen();
    }
  });

  //收信
  rws.addEventListener("message", (e) => {
    webSocketOnMessage(e.data);
  });

  // 错误时进行的处理
  rws.addEventListener("error", (e) => {
    console.error(e.message);
  });

  // 关闭时进行的操作
  rws.addEventListener("close", () => {
    webSocketClose();
  });
}

//连接socket建立时触发
const webSocketOpen = () => {
  console.log("建立成功，发送消息");
  let token = localStorage.getItem('tokenkey');
  if (!isNullOrUndefined(token)) {
    let obj = {
      kind: 1,
      token: token,
      id: 0
    }
    sendSock(obj, () => { });
  }
}

//客户端接收服端数据时触发,e为接受的数据对象
const webSocketOnMessage = (data) => {
  globalCallback(data);//JSON.parse(decrypt(data))
}

//发送数据
const webSocketSend = (data) => {
  rws.send(data);
}

//关闭socket
const webSocketClose = () => {
  rws.close();
  console.log("对话连接已关闭");
}


// 实际调用的方法
const sendSock = (agentData, callback) => {
  console.log("重新连接")
  globalCallback = callback;
  console.log("rws.readyState", rws);
  switch (rws.readyState) {
    //OPEN：值为1，表示连接成功，可以通信了。
    case rws.OPEN:
      console.log("OPEN")
      webSocketSend(agentData);
      break;
    // CONNECTING：值为0，表示正在连接。
    case rws.CONNECTING:
      console.log("CONNECTING", callback)
      setTimeout(function () {
        //@ts-ignore
        webSocketSend(agentData, callback);
      }, 1000);
      break;
    // CLOSING：值为2，表示连接正在关闭。
    case rws.CLOSING:
      console.log("CLOSING")
      setTimeout(() => {
        //@ts-ignore
        webSocketSend(agentData, callback);
      }, 1000);
      break;
    // CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
    case rws.CLOSED:
      console.log("CLOSED")
      // do something
      break;
    default:
      console.log("default")
      break;
  }
}

export { initWebsocket, webSocketClose,webSocketOpen, sendSock,webSocketOnMessage };
